package eu.ec.ellipcis.integration.ws.converter;

import java.io.IOException;
import java.io.StringWriter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import org.springframework.xml.transform.StringSource;

public class AccountMessageConverter implements MessageConverter {

    /* ---- Instance Variables ---- */
    @Autowired
    @Qualifier ("jaxb2Marshaller")
    private Marshaller marshaller = null;

    public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        try {
            marshaller.marshal(object, result);
        } catch (IOException ioException) {
            throw new MessageConversionException(ioException.getMessage());
        }
        return session.createTextMessage(writer.toString());
    }

    public Object fromMessage(Message message) throws JMSException, MessageConversionException {
        Unmarshaller unmarshaller = (Unmarshaller)marshaller;
        TextMessage textMessage = (TextMessage)message;
        try {
            return unmarshaller.unmarshal(new StringSource(textMessage.getText()));
        } catch (XmlMappingException e) {
            throw new MessageConversionException(e.getMessage());
        } catch (IOException e) {
            throw new MessageConversionException(e.getMessage());		}
    }


    /* ---- Getters and Setters ---- */

    public Marshaller getMarshaller() {
        return marshaller;
    }

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }



}
